package org.example.easybuy.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mysql.cj.util.StringUtils;
import org.example.easybuy.dao.OrderDao;
import org.example.easybuy.dao.OrderDetailDao;
import org.example.easybuy.entity.Order;
import org.example.easybuy.entity.OrderDetail;
import org.example.easybuy.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private OrderDetailDao orderDetailDao;

    @Override
    public PageInfo<Order> getOrderPageInfo(Map<String, Object> params) {
        params.put("orderBy","createTime desc");
        params.put("serialNumber","%"+params.get("serialNumber")+"%");
        params.put("createTime","%"+params.get("createTime")+"%");
        if(params.get("userName")!=null)
        {
            params.put("userName","%"+params.get("userName")+"%");
        }
        PageHelper.startPage(params);
        PageInfo<Order> pageInfo=new PageInfo<>(orderDao.selectOrder(params));
        String idList="";
        for(int i=0;i<pageInfo.getList().size();i++)
        {
            idList+=pageInfo.getList().get(i).getId();
            if(i<pageInfo.getList().size()-1)
            {
                idList+=",";
            }

        }
        List<OrderDetail> details=orderDetailDao.selectDetailByIds(idList);
        for(Order o:pageInfo.getList())
        {
            for(OrderDetail detail:details)
            {
                if(o.getId()==detail.getOrderId())
                {
                    o.detailList.add(detail);
                }
            }
        }
        return pageInfo;
    }

    @Override
    public Order selectOrderById(int id) {
        return orderDao.selectOrderById(id);
    }

    @Override
    public boolean updateOrderBySerial(Order order) {
        return orderDao.updateOrderBySerial(order)==1;
    }

    @Override
    public boolean updateOrderStatus(Map<String, Object> params) {
        return orderDao.updateOrderStatus(params)==1;
    }

    @Override
    public boolean addOrder(Order order) {
        return orderDao.addOrder(order)==1;
    }

    @Override
    public Order selectBySerialNumber(String serialNumber) {
        return orderDao.selectBySerialNumber(serialNumber);
    }

    @Override
    public boolean updateOrderStatusById(int id) {
        return orderDao.updateOrderStatusById(id)==1;
    }

}
